package model.roomManagement.Implementation;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;

import model.roomManagement.Interface.IServer;



public class AudioServer implements Runnable{
	public static final int PORT=5000;
	public static int MAX_UDP_DATA_LENGTH=65508;
	
	private DatagramSocket socket;
	private boolean isActive;
	private IServer server;
	
	public AudioServer(IServer server2){
		
		try {
			socket=new DatagramSocket(PORT);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		isActive=true;
		this.server=server2;
		new Thread(this).start();
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("audio start");
		DatagramPacket receivePacket=new DatagramPacket(new byte[MAX_UDP_DATA_LENGTH],MAX_UDP_DATA_LENGTH);
		while(isActive){
			try{
				receivePacket.setLength(MAX_UDP_DATA_LENGTH);
				socket.receive(receivePacket);
				ByteArrayInputStream byteIn=new ByteArrayInputStream(receivePacket.getData(),0,receivePacket.getLength());
				DataInputStream dataIn=new DataInputStream(byteIn);				
				try{
					int userID=dataIn.readInt();
					InetSocketAddress ad=(InetSocketAddress) receivePacket.getSocketAddress();
					System.out.println(userID);
					server.addAudioAddress(userID, ad);//返回boolean
					socket.send(receivePacket);
				}catch(IOException e){
					e.printStackTrace();
				}
			}catch(Throwable e){}
		}
		try{
			socket.close();
		}catch(Throwable e){}
	}
	

	
}
